
# SuperFastPython.com
# example of issuing a task with apply() to the process pool with a return value
from random import random
from time import sleep
from multiprocessing.pool import Pool
 
# task executed in a worker process
def task():
    # generate a value
    value = random()
    # report a message
    print(f'Task executing: {value}', flush=True)
    # block for a moment
    sleep(1)
    # report a message
    # flush=True 的作用是强制将缓冲区的内容立即输出到终端，而不是等待缓冲区满或者程序结束时才输出。
    print(f'Task done {value}', flush=True)
    return value
 
# protect the entry point
if __name__ == '__main__':
    # create and configure the process pool
    pool = Pool()
    # issue tasks to the process pool
    result = pool.apply(task)
    # report value
    print(f'Main got: {result}')
    # close the process pool
    pool.close()